//
//  SettingsView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import Foundation
import SwiftUI
import StoreKit
import UIKit

struct SettingsView: View {
    @EnvironmentObject var dataManager: DataManager
    enum ActiveSheet: Identifiable {
        case language, about, privacy, terms
        var id: Self { self }
    }
    @State private var activeSheet: ActiveSheet? = nil
    @State private var isLoading = false
    @State private var biometricToggleState = false
    @State private var showingAlert = false
    @State private var alertMessage = ""
    
    var body: some View {
        NavigationView {
            VStack(spacing: 0) {
                // 顶部导航
                HStack {
                    Text(dataManager.currentLanguage == "zh" ? "设置" : "Settings")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                    
                    Spacer()
                }
                .padding(.horizontal, 20)
                .padding(.top, 20)
                .padding(.bottom, 15)
                
                ScrollView {
                    VStack(spacing: 20) {
                        // 游客模式或登录提示
                        if dataManager.isGuestMode {
                            guestModeSection
                        } else if dataManager.currentUser == nil {
                            loginPromptSection
                        }
                        
                        // 应用设置
                        appSettingsSection
                        
                        // 关于应用
                        aboutSection
                        
                        // 法律信息
                        legalSection
                        
                        // 登出按钮
                        if dataManager.currentUser != nil || dataManager.isGuestMode {
                            logoutSection
                        }
                    }
                    .padding(.horizontal, 20)
                    .padding(.bottom, 100)
                }
            }
            .background(
                LinearGradient(
                    colors: [
                        Color(red: 0.0, green: 0.0, blue: 0.0),
                        Color(red: 0.05, green: 0.02, blue: 0.08),
                        Color(red: 0.08, green: 0.04, blue: 0.12),
                        Color(red: 0.12, green: 0.06, blue: 0.15),
                        Color(red: 0.15, green: 0.08, blue: 0.18),
                        Color(red: 0.18, green: 0.10, blue: 0.20),
                        Color(red: 0.20, green: 0.12, blue: 0.22),
                        Color(red: 0.22, green: 0.14, blue: 0.25)
                    ],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
            )
            .preferredColorScheme(.dark)
            .navigationBarHidden(true)
        }
        .sheet(item: $activeSheet) { sheet in
            switch sheet {
            case .language:
                LanguageSelectionView()
            case .about:
                AboutView()
            case .privacy:
                PrivacyPolicyView()
            case .terms:
                TermsOfServiceView()
            }
        }
        .alert("Alert", isPresented: $showingAlert) {
            Button("OK") { }
        } message: {
            Text(alertMessage)
        }
        .onReceive(dataManager.$currentUser) { user in
            if let user = user {
                biometricToggleState = user.biometricLoginEnabled
            }
        }
    }

    
    // MARK: - 生物识别设置行
    private var biometricSettingsRow: some View {
        HStack(spacing: 15) {
            Image(systemName: "faceid")
                .font(.title3)
                .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                .frame(width: 24, height: 24)
            
            VStack(alignment: .leading, spacing: 2) {
                Text(dataManager.currentLanguage == "zh" ? "生物识别登录" : "Biometric Login")
                    .font(.headline)
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity, alignment: .leading)
                
                Text(dataManager.currentLanguage == "zh" ? "使用Face ID或Touch ID登录" : "Use Face ID or Touch ID to login")
                    .font(.caption)
                    .foregroundColor(.gray)
                    .frame(maxWidth: .infinity, alignment: .leading)
            }
            
            Spacer()
            
            if let user = dataManager.currentUser {
                HStack {
                    Toggle("", isOn: $biometricToggleState)
                        .disabled(isLoading)
                        .onChange(of: biometricToggleState) { newValue in
                            if newValue != user.biometricLoginEnabled {
                                if newValue {
                                    enableBiometricLogin()
                                } else {
                                    disableBiometricLogin()
                                }
                            }
                        }
                        .onAppear {
                            biometricToggleState = user.biometricLoginEnabled
                        }
                    
                    if isLoading {
                        ProgressView()
                            .scaleEffect(0.8)
                            .progressViewStyle(CircularProgressViewStyle(tint: .orange))
                    }
                }
            }
        }
        .padding(16)
    }
    
    // MARK: - 应用设置
    private var appSettingsSection: some View {
        VStack(spacing: 15) {
            HStack {
                Text(dataManager.currentLanguage == "zh" ? "应用设置" : "App Settings")
                    .font(.headline)
                    .fontWeight(.bold)
                    .foregroundColor(.white)
                
                Spacer()
            }
            
            VStack(spacing: 0) {
                // 语言设置
                SettingsRowView(
                    icon: "globe",
                    title: dataManager.currentLanguage == "zh" ? "语言" : "Language",
                    subtitle: dataManager.currentLanguage == "zh" ? "简体中文" : "English",
                    action: {
                        activeSheet = .language
                    }
                )
                
                Divider()
                    .background(Color.gray.opacity(0.3))
                    .padding(.horizontal, 16)
                
                // 通知设置
                SettingsRowView(
                    icon: "bell",
                    title: dataManager.currentLanguage == "zh" ? "通知设置" : "Notifications",
                    subtitle: dataManager.currentLanguage == "zh" ? "管理推送通知" : "Manage push notifications",
                    action: {
                        if let url = URL(string: UIApplication.openSettingsURLString) {
                            UIApplication.shared.open(url)
                        }
                    }
                )
                
                Divider()
                    .background(Color.gray.opacity(0.3))
                    .padding(.horizontal, 16)
                
                // 生物识别设置
                biometricSettingsRow
                
            }
            .background(
                RoundedRectangle(cornerRadius: 12)
                    .fill(
                        LinearGradient(
                            colors: [
                                Color(red: 0.15, green: 0.15, blue: 0.15),
                                Color(red: 0.1, green: 0.1, blue: 0.1),
                                Color(red: 0.05, green: 0.05, blue: 0.05)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
            )
        }
    }
    
    // MARK: - 关于应用
    private var aboutSection: some View {
        VStack(spacing: 15) {
            HStack {
                Text(dataManager.currentLanguage == "zh" ? "关于" : "About")
                    .font(.headline)
                    .fontWeight(.bold)
                    .foregroundColor(.white)
                
                Spacer()
            }
            
            VStack(spacing: 0) {
                // 关于应用
                SettingsRowView(
                    icon: "info.circle",
                    title: dataManager.currentLanguage == "zh" ? "关于应用" : "About App",
                    subtitle: "Version 1.0.0",
                    action: {
                        activeSheet = .about
                    }
                )
                
                Divider()
                    .background(Color.gray.opacity(0.3))
                    .padding(.horizontal, 16)
                
                // 联系我们
                SettingsRowView(
                    icon: "envelope",
                    title: dataManager.currentLanguage == "zh" ? "联系我们" : "Contact Us",
                    subtitle: AppConfig.contactEmail,
                    action: {
                        if let url = URL(string: "mailto:\(AppConfig.contactEmail)") {
                            UIApplication.shared.open(url)
                        }
                    }
                )
                
                Divider()
                    .background(Color.gray.opacity(0.3))
                    .padding(.horizontal, 16)
                
                // 评价应用
                SettingsRowView(
                    icon: "star",
                    title: dataManager.currentLanguage == "zh" ? "评价应用" : "Rate App",
                    subtitle: dataManager.currentLanguage == "zh" ? "在App Store评价" : "Rate on App Store",
                    action: {
                        if let windowScene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene {
                            SKStoreReviewController.requestReview(in: windowScene)
                        }
                    }
                )
            }
            .background(
    RoundedRectangle(cornerRadius: 12)
        .fill(
            LinearGradient(
                colors: [
                    Color(red: 0.15, green: 0.15, blue: 0.15),
                    Color(red: 0.1, green: 0.1, blue: 0.1),
                    Color(red: 0.05, green: 0.05, blue: 0.05)
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
        )
)
        }
    }
    
    // MARK: - 法律信息
    private var legalSection: some View {
        VStack(spacing: 15) {
            HStack {
                Text(dataManager.currentLanguage == "zh" ? "法律信息" : "Legal")
                    .font(.headline)
                    .fontWeight(.bold)
                    .foregroundColor(.white)
                
                Spacer()
            }
            
            VStack(spacing: 0) {
                // 隐私政策
                SettingsRowView(
                    icon: "lock.shield",
                    title: dataManager.currentLanguage == "zh" ? "隐私政策" : "Privacy Policy",
                    subtitle: dataManager.currentLanguage == "zh" ? "了解我们如何保护您的隐私" : "Learn how we protect your privacy",
                    action: {
                        activeSheet = .privacy
                    }
                )
                
                Divider()
                    .background(Color.gray.opacity(0.3))
                    .padding(.horizontal, 16)
                
                // 服务条款
                SettingsRowView(
                    icon: "doc.text",
                    title: dataManager.currentLanguage == "zh" ? "服务条款" : "Terms of Service",
                    subtitle: dataManager.currentLanguage == "zh" ? "查看使用条款" : "View terms of use",
                    action: {
                        activeSheet = .terms
                    }
                )
            }
            .background(
    RoundedRectangle(cornerRadius: 12)
        .fill(
            LinearGradient(
                colors: [
                    Color(red: 0.15, green: 0.15, blue: 0.15),
                    Color(red: 0.1, green: 0.1, blue: 0.1),
                    Color(red: 0.05, green: 0.05, blue: 0.05)
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
        )
)
        }
    }
    

    
    // MARK: - 游客模式区域
    private var guestModeSection: some View {
        VStack(spacing: 15) {
            Image(systemName: "person.fill.questionmark")
                .font(.largeTitle)
                .foregroundColor(.white.opacity(0.6))
            
            Text(dataManager.currentLanguage == "zh" ? "游客模式" : "Guest Mode")
                .font(.headline)
                .foregroundColor(.white)
            
            Text(dataManager.currentLanguage == "zh" ? "登录后可享受更多功能和会员特权" : "Login for more features and member benefits")
                .font(.subheadline)
                .foregroundColor(.white.opacity(0.7))
                .multilineTextAlignment(.center)
            
            NavigationLink(destination: LoginView()) {
                Text(dataManager.currentLanguage == "zh" ? "立即登录" : "Login Now")
                    .font(.headline)
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .frame(height: 50)
                    .background(
                        LinearGradient(
                            colors: [
                                Color(red: 1.0, green: 0.6, blue: 0.2),
                                Color(red: 1.0, green: 0.5, blue: 0.1)
                            ],
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    )
                    .cornerRadius(12)
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(
                    LinearGradient(
                        colors: [
                            Color(red: 0.15, green: 0.15, blue: 0.15),
                            Color(red: 0.1, green: 0.1, blue: 0.1),
                            Color(red: 0.05, green: 0.05, blue: 0.05)
                        ],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
        )
    }
    
    // MARK: - 登录提示区域
    private var loginPromptSection: some View {
        VStack(spacing: 15) {
            Image(systemName: "person.badge.plus")
                .font(.largeTitle)
                .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
            
            Text(dataManager.currentLanguage == "zh" ? "请先登录" : "Please Login First")
                .font(.headline)
                .foregroundColor(.white)
            
            Text(dataManager.currentLanguage == "zh" ? "登录后可使用完整功能" : "Login to use full features")
                .font(.subheadline)
                .foregroundColor(.white.opacity(0.7))
                .multilineTextAlignment(.center)
            
            NavigationLink(destination: LoginView()) {
                Text(dataManager.currentLanguage == "zh" ? "立即登录" : "Login Now")
                    .font(.headline)
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .frame(height: 50)
                    .background(
                        LinearGradient(
                            colors: [
                                Color(red: 1.0, green: 0.6, blue: 0.2),
                                Color(red: 1.0, green: 0.5, blue: 0.1)
                            ],
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    )
                    .cornerRadius(12)
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(
                    LinearGradient(
                        colors: [
                            Color(red: 0.15, green: 0.15, blue: 0.15),
                            Color(red: 0.1, green: 0.1, blue: 0.1),
                            Color(red: 0.05, green: 0.05, blue: 0.05)
                        ],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
        )
    }
    
    // MARK: - 登出区域
    private var logoutSection: some View {
        Button(action: {
            dataManager.logout()
        }) {
            HStack {
                Image(systemName: "rectangle.portrait.and.arrow.right")
                    .font(.title3)
                    .foregroundColor(.red)
                
                Text(dataManager.isGuestMode ? 
                     (dataManager.currentLanguage == "zh" ? "退出游客模式" : "Exit Guest Mode") :
                     (dataManager.currentLanguage == "zh" ? "退出登录" : "Sign Out"))
                    .font(.headline)
                    .fontWeight(.medium)
                    .foregroundColor(.red)
                
                Spacer()
            }
            .padding(16)
            .background(
    RoundedRectangle(cornerRadius: 12)
        .fill(
            LinearGradient(
                colors: [
                    Color(red: 0.15, green: 0.15, blue: 0.15),
                    Color(red: 0.1, green: 0.1, blue: 0.1),
                    Color(red: 0.05, green: 0.05, blue: 0.05)
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
        )
)
        }
    }
}

// MARK: - 设置行视图
struct SettingsRowView: View {
    let icon: String
    let title: String
    let subtitle: String
    let action: () -> Void
    
    var body: some View {
        Button(action: action) {
            HStack(spacing: 15) {
                Image(systemName: icon)
                    .font(.title3)
                    .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                    .frame(width: 24, height: 24)
                
                VStack(alignment: .leading, spacing: 2) {
                    Text(title)
                        .font(.headline)
                        .foregroundColor(.white)
                        .frame(maxWidth: .infinity, alignment: .leading)
                    
                    Text(subtitle)
                        .font(.caption)
                        .foregroundColor(.gray)
                        .frame(maxWidth: .infinity, alignment: .leading)
                }
                
                Image(systemName: "chevron.right")
                    .font(.caption)
                    .foregroundColor(.gray)
            }
            .padding(16)
        }
        .buttonStyle(PlainButtonStyle())
    }
}

// MARK: - 语言选择视图
struct LanguageSelectionView: View {
    @EnvironmentObject var dataManager: DataManager
    @Environment(\.dismiss) private var dismiss
    
    private let languages = [
        ("zh", "简体中文", "Chinese (Simplified)"),
        ("en", "English", "English")
    ]
    
    var body: some View {
        NavigationView {
            ZStack {
                Color(red: 0.08, green: 0.08, blue: 0.08)
                    .ignoresSafeArea()
                
                VStack(spacing: 0) {
                    ForEach(languages, id: \.0) { language in
                        Button(action: {
                            dataManager.setLanguage(language.0)
                            dismiss()
                        }) {
                            HStack {
                                VStack(alignment: .leading, spacing: 4) {
                                    Text(language.1)
                                        .font(.headline)
                                        .foregroundColor(.white)
                                    
                                    Text(language.2)
                                        .font(.caption)
                                        .foregroundColor(.gray)
                                }
                                
                                Spacer()
                                
                                if dataManager.currentLanguage == language.0 {
                                    Image(systemName: "checkmark")
                                        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                                }
                            }
                            .padding(16)
                        }
                        .buttonStyle(PlainButtonStyle())
                        
                        if language.0 != languages.last?.0 {
                            Divider()
                                .background(Color.gray.opacity(0.3))
                        }
                    }
                }
                .background(
                    RoundedRectangle(cornerRadius: 12)
                        .fill(
                            LinearGradient(
                                colors: [
                                    Color(red: 0.15, green: 0.15, blue: 0.15),
                                    Color(red: 0.1, green: 0.1, blue: 0.1),
                                    Color(red: 0.05, green: 0.05, blue: 0.05)
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                )
                .padding(20)
            }
            .navigationTitle(dataManager.currentLanguage == "zh" ? "选择语言" : "Select Language")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(dataManager.currentLanguage == "zh" ? "完成" : "Done") {
                        dismiss()
                    }
                    .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                }
            }
        }
    }
}

// MARK: - SettingsView 生物识别功能扩展

// MARK: - 关于应用视图
struct AboutView: View {
    @EnvironmentObject var dataManager: DataManager
    @Environment(\.dismiss) private var dismiss
    
    var body: some View {
        NavigationView {
            ZStack {
                Color(red: 0.08, green: 0.08, blue: 0.08)
                    .ignoresSafeArea()
                
                ScrollView {
                    VStack(spacing: 30) {
                        // Logo
                        Image("Logo")
                            .resizable()
                            .scaledToFit()
                            .frame(width: 80, height: 80)
                        
                        VStack(spacing: 10) {
                            Text("CU MR BULL")
                                .font(.title)
                                .fontWeight(.bold)
                                .foregroundColor(.white)
                            
                            Text(dataManager.currentLanguage == "zh" ? "健康韩式快餐" : "Power Up with Every Bite!")
                                .font(.headline)
                                .foregroundColor(.gray)
                        }
                        
                        VStack(spacing: 15) {
                            Text(dataManager.currentLanguage == "zh" ? "版本信息" : "Version Information")
                                .font(.headline)
                                .foregroundColor(.white)
                            
                            VStack(spacing: 8) {
                                Text("Version 1.0.0")
                                    .foregroundColor(.gray)
                                
                                Text("Build 2025.01.16")
                                    .foregroundColor(.gray)
                            }
                        }
                        
                        Text("© 2025 Cu Mr Bull Pte. Ltd.")
                            .font(.caption)
                            .foregroundColor(.gray)
                    }
                    .padding(20)
                }
            }
            .navigationTitle(dataManager.currentLanguage == "zh" ? "关于应用" : "About App")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(dataManager.currentLanguage == "zh" ? "完成" : "Done") {
                        dismiss()
                    }
                    .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                }
            }
        }
    }
}

// MARK: - SettingsView 生物识别功能扩展
extension SettingsView {
    private func enableBiometricLogin() {
        // 首先检查生物识别是否可用
        guard dataManager.isBiometricAvailable() else {
            self.alertMessage = dataManager.currentLanguage == "zh" ? "生物识别功能不可用" : "Biometric authentication not available"
            self.showingAlert = true
            self.biometricToggleState = false
            return
        }
        
        self.isLoading = true
        
        dataManager.authenticateWithBiometrics { [self] (success: Bool, error: String?) in
            DispatchQueue.main.async {
                self.isLoading = false
                
                if success {
                    // 验证成功后启用生物识别
                    self.dataManager.enableBiometricLogin()
                    // 确保Toggle状态与实际状态同步
                    self.biometricToggleState = true
                    
                    if AppConfig.enableDebugLogging {
                        print("[DEBUG] SettingsView: 生物识别登录已启用")
                    }
                } else {
                    // 验证失败，恢复Toggle状态并显示错误信息
                    self.biometricToggleState = false
                    let errorMsg = error ?? (self.dataManager.currentLanguage == "zh" ? "需要验证身份才能启用生物识别" : "Authentication required to enable biometric login")
                    self.alertMessage = errorMsg
                    self.showingAlert = true
                    
                    if AppConfig.enableDebugLogging {
                        print("[DEBUG] SettingsView: 启用生物识别验证失败 - \(errorMsg)")
                    }
                }
            }
        }
    }
    
    private func disableBiometricLogin() {
        // 首先检查生物识别是否可用
        guard dataManager.isBiometricAvailable() else {
            self.alertMessage = dataManager.currentLanguage == "zh" ? "生物识别功能不可用" : "Biometric authentication not available"
            self.showingAlert = true
            self.biometricToggleState = true
            return
        }
        
        self.isLoading = true
        
        dataManager.authenticateWithBiometrics { [self] (success: Bool, error: String?) in
            DispatchQueue.main.async {
                self.isLoading = false
                
                if success {
                    // 验证成功后禁用生物识别
                    self.dataManager.disableBiometricLogin()
                    // 确保Toggle状态与实际状态同步
                    self.biometricToggleState = false
                    
                    if AppConfig.enableDebugLogging {
                        print("[DEBUG] SettingsView: 生物识别登录已禁用")
                    }
                } else {
                    // 验证失败，恢复Toggle状态并显示错误信息
                    self.biometricToggleState = true
                    let errorMsg = error ?? (self.dataManager.currentLanguage == "zh" ? "需要验证身份才能禁用生物识别" : "Authentication required to disable biometric login")
                    self.alertMessage = errorMsg
                    self.showingAlert = true
                    
                    if AppConfig.enableDebugLogging {
                        print("[DEBUG] SettingsView: 禁用生物识别验证失败 - \(errorMsg)")
                    }
                }
            }
        }
    }
}

#Preview {
    SettingsView()
        .environmentObject(DataManager.shared)
}